<template>
  <div class="main">
    <section v-if="baseMsgForm">
      <div class="btn-box">
        <h3>商品查看</h3>
        <div>
          <el-button class="filter-item" v-if="isEdit" type="success" size="small" @click="save">保存</el-button>
          <el-button class="filter-item" v-else @click="updateUpshelf" type="danger" size="small">下架</el-button>
        </div>
      </div>
      <div class="mask_container">
        <div class="mask" v-show="!isEdit"></div>

        <el-tabs v-model="activeName">
          <el-tab-pane label="基础信息" name="first">
            <el-form :model="baseMsgForm" ref="baseMsgForm" label-width="120px" class="demo-baseMsgForm">
              <el-form-item label="商品款号:" prop="serialNo">
                <span>{{baseMsgForm.serialNo}}</span>
              </el-form-item>
              <el-form-item label="ERP商品名称:" prop="erpGoodsName">
                <span>{{baseMsgForm.erpGoodsName}}</span>
              </el-form-item>
              <el-form-item label="后台分类:" prop="goodsName">
                <span>{{baseMsgForm.backCatName}}</span>
              </el-form-item>
              <el-form-item label="商品名称:" :rules="commonRules.notNullRule" prop="name">
                <el-input placeholder="请输入商品名称" v-model="baseMsgForm.name" />
              </el-form-item>
              <el-form-item label="商品副标题:" :rules="commonRules.notNullRule" prop="subName">
                <el-input placeholder="请输入商品副标题" v-model="baseMsgForm.subName" />
              </el-form-item>
              <el-form-item label="经营模式:" :rules="commonRules.notNullRule">
                <el-select v-model="baseMsgForm.businessModel" placeholder="请选择">
                  <el-option label="招商" :value="0"></el-option>
                  <el-option label="自营" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="品牌:">
                <el-select v-model="baseMsgForm.brandId" filterable placeholder="请选择">
                  <el-option v-for="it in brands" :key="it.id" :label="it.name" :value="it.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="供应商:" :rules="commonRules.notNullRule">
                <el-select v-model="baseMsgForm.storehouseId" filterable placeholder="请选择">
                  <el-option v-for="it in merchants" :key="it.supplyCode" :label="it.merchantName" :value="it.ckdm"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="仓库:" :rules="commonRules.notNullRule">
                <el-select v-model="baseMsgForm.merchantId" filterable placeholder="请选择">
                  <el-option v-for="it in merchants" :key="it.ckdm" :label="it.merchantName" :value="it.ckdm"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="运费模板:" :rules="commonRules.notNullRule">
                <el-select v-model="baseMsgForm.freightTemplateId" filterable placeholder="请选择">
                  <el-option v-for="it in freightList" :key="it.id" :label="it.name" :value="it.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="标签:">
                <span>{{baseMsgForm.goodsTags || '暂无'}}</span>
              </el-form-item>
              <el-form-item label="是否上架:" prop="upShelf" :rules="commonRules.notNullRule">
                <el-switch v-model="baseMsgForm.upShelf" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item label="是否售卖:" prop="onSale">
                <el-radio-group v-model="baseMsgForm.onSale">
                  <el-radio :label="1">是,立即售卖</el-radio>
                  <el-radio :label="2">否,定时售卖</el-radio>
                  <el-radio :label="3">仅上架,不售卖</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="baseMsgForm.onSale === 2" label="开售时间:" prop="onSaleTime">
                <el-date-picker value-format="timestamp" v-model="baseMsgForm.onSaleTime" type="date" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="是否允许搜索:" prop="canSearch">
                <el-switch :active-value="1" :inactive-value="0" v-model="baseMsgForm.canSearch"></el-switch>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品描述" name="second">
            <el-form :model="baseMsgForm" ref="baseMsgForm" label-width="120px" class="demo-baseMsgForm">
              <el-form-item label="商品主图:" :rules="commonRules.notNullRule">
                <MyUpload v-model="baseMsgForm.mainPic" />
              </el-form-item>
              <el-form-item label="列表封面图:" :rules="commonRules.notNullRule">
                <MyUpload v-model="baseMsgForm.coverPic" />
              </el-form-item>
              <el-form-item label="商品图:" :rules="commonRules.notNullRule">
                <MyUpload v-model="baseMsgForm.picSet" :limit='5' />
              </el-form-item>
              <el-form-item label="商品详情" :rules="commonRules.notNullRule">
                <tinymce :height="360" v-model="baseMsgForm.description"></tinymce>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="third">
            <el-form :model="baseMsgForm" label-width="120px">
              <el-form-item label="属性组:" :rules="commonRules.notNullRule">
                <span>{{baseMsgForm.backCatName}}</span>
                <el-button type="primary" size="mini" @click="chooseProp">选择属性组</el-button>
              </el-form-item>
              <el-form-item label="自定义规格:" :rules="commonRules.notNullRule">
                <div class="specificaiton">
                  <div v-for="it in currentChildrenCat" :key="it.id">
                    <template v-if="it.inputType === 0">
                      <div class="specificaiton_title">{{it.name}}</div>
                      <div class="cat_input" v-for="(cat, idx) in it.inputs" :key="idx">
                        <el-input style="width:100px;margin:0 10px" size='mini' v-model="it.inputs[idx]" />
                        <span class="error" @click="deleteCat(it,idx)">×</span>
                      </div>
                      <!-- 这个新增按钮并不会在属性组中新增子属性，但当对应规格明细列表选择新增属性的时候，再次进来详情要从规格明细列表中遍历取出属性组没有的属性 -->
                      <el-button type="primary" size="mini" @click="addCat(it)">新增</el-button>
                    </template>
                    <template v-else>
                      <div class="specificaiton_title">{{it.name}}</div>
                      <el-tag style="margin:0 10px" v-for="(cat, idx) in it.inputs" :key="idx">
                        {{cat}}
                      </el-tag>
                    </template>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="规格明细:" v-if="baseMsgForm.goodsSkuList&&baseMsgForm.goodsSkuList.length > 0">
                <Specifications :data.sync="baseMsgForm.goodsSkuList" :catArr='currentChildrenCat' />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <div class="btn-box" v-show="this.isEdit">
        <div>
          <el-button class="filter-item"  v-if="isEdit" type="success" size="small" @click="save">保存</el-button>
          <el-button class="filter-item" v-else @click="updateUpshelf" type="danger" size="small">下架</el-button>
        </div>
      </div>
      <el-dialog title="选择属性组" :visible.sync="catDialogVisible">
        <el-table border :data="catList" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
          <el-table-column prop="name" label="当前选择">
            <template slot-scope="scope">
              <label class="input-radio">
                <input type="radio" :value="scope.row" v-model="currentCat" />
                <span></span>
              </label>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="属性组名称">
          </el-table-column>
          <el-table-column prop="description" label="属性组描述">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="catDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="getCurrentCat">确 定</el-button>
        </span>
      </el-dialog>
    </section>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MyUpload from '@/components/Upload/myUpload'
import Specifications from './components/specifications'
import {
  getGoodsDetail,
  getBrandList,
  updateGoods,
  getCatBindAttr,
  getAttr,
  updateUpSelfStatus
} from '@/api/goodMiddleStage'
import { getMerchantWarehouse } from '@/api/common'
import { getAllList } from '@/api/freight' // 运费模板
export default {
  data() {
    return {
      catList: [], // 当前商品绑定属性组
      currentCat: {}, // 当前选择属性组
      currentChildrenCat: [],
      merchants: [], //供应商
      freightList: [], //运费模板
      brands: [], //品牌
      dialogImageUrl: '',
      dialogVisible: false,
      catDialogVisible: false,
      activeName: 'first',
      baseMsgForm: null,
      isEdit: true
    }
  },
  components: {
    Tinymce,
    MyUpload,
    Specifications
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getMerchantWarehouseList() // 获取供应商
      this.getAllTpl() // 运费模板
      this._getBrandList() // 品牌获取
      this.getData()
    },
    async getData() {
      try {
        const { data } = await getGoodsDetail({
          goodsId: this.$route.query.goodsId
        })
        this.baseMsgForm = data
        this.isEdit = (data.upShelf === 0)
        // 当前已经绑定了子属性 查询子属性信息 带出相关属性和属性值
        if (this.baseMsgForm.goodsAttrGroupId) {
          // 生成子属性
          this.getCurrentCat()
        }
        console.log(data)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取供应商、仓库列表
    async getMerchantWarehouseList() {
      const { data } = await getMerchantWarehouse()
      this.merchants = data.viewList.filter(item => item.supplyCode !== null)
    },
    // 品牌获取
    async _getBrandList() {
      try {
        const { data } = await getBrandList()
        this.brands = data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取运费模板列表 ,
    async getAllTpl() {
      try {
        const { code, data, msg } = await getAllList()
        if (code == 0) {
          this.freightList = data
        } else {
          this.$message({
            type: 'error',
            message: msg,
            duration: 2000
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '未知错误',
          duration: 2000
        })
      }
    },
    // 获取商品绑定属性组
    async _getCatBindAttr() {
      try {
        const { data } = await getCatBindAttr({
          backCatId: this.$route.query.backCatId
        })
        this.catList = data.goodsAttrGroupList

        console.log('属性组', data)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取当前所选属性
    async getCurrentCat() {
      if (this.currentCat.id) {
        this.baseMsgForm.goodsAttrGroupId = this.currentCat.id
      }
      if (!this.baseMsgForm.goodsAttrGroupId) {
        return this.$message.error('请选择属性')
      }
      try {
        const { data } = await getAttr({
          attrGroupId: this.baseMsgForm.goodsAttrGroupId
        })
        this.currentChildrenCat = data.attrList.map(it => {
          if (!it.inputs) {
            it.inputs = []
          }
          return it
        })
        this.generateCat()
        this.catDialogVisible = false
        console.log('当前属性组', data)
      } catch (error) {
        console.log(error)
      }
    },
    /* 
      生成规格明细自定义属性项。
      说明：列表所带来的自定义属性值在属性组的子属性中可能不存在，因此要遍历出不存在的自定义值加入到当前子属性组 
     */
    generateCat() {
      const { goodsSkuList } = this.baseMsgForm
      this.currentChildrenCat = this.currentChildrenCat.map(it => {
        goodsSkuList.forEach(arr => {
          let { attrInfo } = arr
          if (attrInfo && attrInfo.length > 0) {
            attrInfo.forEach(val => {
              // 判断是否有相同属性， 子属性组不存在该值就新增该值
              if (
                it.name === val.attrName &&
                !it.inputs.includes(val.attrValue)
              ) {
                it.inputs.push(val.attrValue)
              }
            })
          }
        })
        return it
      })
    },
    //商品上下架
    async updateUpshelf() {
      try {
        const { data } = await updateUpSelfStatus({
          goodsId: this.baseMsgForm.goodsId,
          upShelf: Number(!this.baseMsgForm.upShelf)
        })
        console.log(data)
        this.$message.success('操作成功')
        this.getData()
      } catch (error) {
        console.log(error)
      }
    },
    handleCurrentChange(val) {
      this.currentCat = val
    },
    // 手动输入新增
    addCat(val) {
      val.inputs.push('')
      console.log(val)
    },
    // 手动输入属性 删除
    deleteCat(val, idx) {
      val.inputs && val.inputs.splice(idx, 1)
    },
    async save() {
      console.log('xx', this.baseMsgForm)
      try {
        const { data } = await updateGoods(this.baseMsgForm)
        this.$message.success('操作成功')
        this.getData()
        console.log('保存信息', data)
      } catch (error) {
        this.$message.error('操作失败')
        console.log(error)
      }
    },
    // 选择属性组
    chooseProp() {
      this.catDialogVisible = true
      if (this.catList.length === 0) {
        this._getCatBindAttr()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-box {
  display: flex;
  justify-content: space-between;
}
.mask_container {
  position: relative;
  width: 100%;
  height: 100%;
}
.mask {
  position: absolute;
  z-index: 99;
  top: 40px;
  left: 0;
  width: 100%;
  height: 95%;
  background: rgba($color: #000000, $alpha: 0.1);
}
.cat_input {
  position: relative;
  display: inline-block;
  margin-bottom: 10px;
  .error {
    cursor: pointer;
    position: absolute;
    top: 0px;
    right: 7px;
    display: inline-block;
    width: 20px;
    height: 20px;
    background: red;
    z-index: 98;
    line-height: 20px;
    text-align: center;
    border-radius: 50%;
    color: #fff;
    font-size: 22px;
  }
}
.specificaiton {
  width: 60%;
  border: 1px solid #d4cbcb;
}
.specificaiton_title{
  background: #F2F2F2;
}
</style>
 